<?php
/**
 * Created by 2019/4/13 0013
 * Effect: TokenValidationMiddleware.php
 * Author: 品花
 * Date: 2019/4/13 0013
 * Time: 上午 10:37
 */

namespace Middleware;


use Consts\RedisKey;
use Helper\Config;
use Helper\Output;
use Helper\Mysql;
use Helper\Redis;
use Helper\Reg;

class ServiceMiddleware
{
    protected static $instance;

    public static function getInstance()
    {
        if ( !isset(self::$instance)) {
            self::$instance = new static();
        }
        return self::$instance;
    }


    /**
     * 上线
     * @param $admin_user
     * @param $fd
     */
    public function online($admin_user , $fd){
        //验证该用户是否已经在线
        $old_fd = Redis::getInstance()->hGet(RedisKey::WS_SERVICE_AUID_TO_FD,$admin_user->id);
        if($old_fd){
            //挤掉线
            Reg::getInstance()->get('server')->disconnect($old_fd);
        }
        $ids = explode(',',$admin_user->problem_ids);
        foreach ($ids as $id){
            Redis::getInstance()->sAdd(RedisKey::platform_online_service($admin_user->platform_id ,$id) , $admin_user->id);
        }

        Redis::getInstance()->hSet(RedisKey::WS_SERVICE_FD_TO_AUID,$fd,$admin_user->id);
        Redis::getInstance()->hSet(RedisKey::WS_SERVICE_AUID_TO_FD, $admin_user->id,$fd);

        Mysql::getInstance()->where('id',$admin_user->id)->update('admin_user',['is_online'=> 1]);

    }

    /**
     * 离线
     * @param $fd
     */
    public function offline($fd){

        go(function () use ($fd){
            $suid = Redis::getInstance()->hGet(RedisKey::WS_SERVICE_FD_TO_AUID,$fd);
            Redis::getInstance()->hDel(RedisKey::WS_SERVICE_FD_TO_AUID,$fd);
            Redis::getInstance()->hDel(RedisKey::WS_SERVICE_AUID_TO_FD,$suid);
            $user = Redis::getInstance()->hGet(RedisKey::ADMIN_SERVICE_INFO_LIST,'id:'.$suid);
            $user = json_decode($user ,true);

            $ids = explode(',',$user['problem_ids']);

            foreach ($ids as $id){
                Redis::getInstance()->sRem(RedisKey::platform_online_service($user['platform_id'] ,$id) , $user['id']);
            }

            Mysql::getInstance()->where('id',$suid)->update('admin_user',['is_online'=> 0]);
        });

    }





}

